package router

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"z-blog/database"
)

func Router(r *gin.Engine) *gin.Engine {
	user := r.Group("/v1")
	userRouter(user)
	admin := r.Group("/v2")
	admin.Use(authUser())
	adminRouter(admin)
	return r
}

func userRouter(r *gin.RouterGroup) {
	r.POST("/login", login)
	r.POST("/get_article_details", getArticleDetails)
	r.GET("/getSorts", getSorts)
	r.GET("/getArticleList", getArticleList)
	r.POST("/pagingFind", pagingFind)
	//根据分类查询文章列表
	r.POST("/getClassifyList", getClassifyList)
	//分类分页查询
	r.POST("/getClassifyPaging", getClassifyPaging)
	//搜索文章接口
	r.POST("/searchArticle", searchArticle)
}

func adminRouter(r *gin.RouterGroup) {
	r.POST("/auth", auth)
	r.POST("/addSort", addSort)
	r.GET("/getSorts", getSorts)
	r.POST("/deleteSort", deleteSort)
	r.POST("/sortMenu", sortMenu)
	r.POST("/releaseArticle", releaseArticle)
	r.GET("/getArticleList", getArticleList)
	r.POST("/pagingFind", pagingFind)
	r.POST("/deleteArticle", deleteArticle)
	//查询文章内容
	r.POST("/findArticleInfo", findArticleInfo)
	//更新文章
	r.POST("/updateArticle", updateArticle)
}

//校验token正确性
func authUser() func(c *gin.Context) {
	return func(c *gin.Context) {
		token := c.GetHeader("token")
		username := c.GetHeader("username")
		res := database.AuthToken(username, token)
		if res {
			c.Next()
		} else {
			c.JSON(http.StatusBadRequest, nil)
		}
	}
}
